<template>
  <div class="mb20">
    <div class="flex-center mb12">
      <Title title="未发文通知设置" font-size="16px"/>
      <PlainCreateBtn @click="handleCreate">新建</PlainCreateBtn>
    </div>
    <u-table
      v-loading="loading"
      v-if="list && list.items.length > 0"
      ref="tableRef"
      :border="false"
      :row-height="49"
      :data="list.items"
      use-virtual
      class="fb-table"
      empty-text="暂无数据"
      fit
      row-key="id"
      hightlight-current-row>
      <u-table-column align="left" label="规则名称" min-width="100">
        <template slot-scope="scope">
          <ToolTip :content="scope.row.ruleName"/>
        </template>
      </u-table-column>
      <u-table-column align="left" label="未发文天数" width="100">
        <template slot-scope="scope">
          <span>{{ scope.row.unpublishedDays || '--' }}</span>
        </template>
      </u-table-column>
      <u-table-column align="left" label="通知人员">
        <template slot-scope="scope">
          <CheckUserInfo v-if="scope.row.noticePerson" :multiple="true" :user-list="scope.row.noticePerson" :label-name="'name'" />
          <ToolTip v-else :content=" formatUser(scope.row.noticePerson)"/>
        </template>
      </u-table-column>
      <u-table-column align="left" label="循环通知" width="100">
        <template slot-scope="scope">
          <span>{{ scope.row.isLoop ? '是' : '否' }}</span>
        </template>
      </u-table-column>
      <u-table-column align="left" prop="creator" label="创建人" width="100">
        <template slot-scope="scope">
          <CheckUserInfo v-if="scope.row.creatorId" :user-id="scope.row.creatorId" :label="scope.row.creator" />
          <ToolTip v-else :content="scope.row.creator"/>
        </template>
      </u-table-column>
      <u-table-column prop="createTime" align="left" label="创建时间" width="200">
        <template slot-scope="scope">
          <div>
            <span v-if="scope.row.createTime">{{ scope.row.createTime | format('YYYY/MM/DD HH:mm:ss') }}</span>
            <span v-else>--</span>
          </div>
        </template>
      </u-table-column>
      <el-table-column
        :width="showMobilePage ? 110 : 140"
        align="center"
        fixed="right"
        label="操作">
        <template slot-scope="scope">
          <div class="operator-btn" style="padding: 0 10px;">
            <el-button type="text" @click="handleCopy(scope.row)"><span style="font-size:14px;">复制</span></el-button>
            <el-button type="text" @click="handleEdit(scope.row)"><span style="font-size:14px;">编辑</span></el-button>
            <el-button type="text" @click="handleDelete(scope.row)"><span style="font-size:14px;">删除</span></el-button>
          </div>
        </template>
      </el-table-column>
    </u-table>
    <empty-placeholder v-else style="margin-bottom: 24px" />
    <el-row v-if="list.total > 0" type="flex" justify="end">
      <el-pagination
        :page-size="perPage"
        :current-page="page"
        :page-sizes="[10,20, 50, 100, 250, 500]"
        :small="showMobilePage"
        :total="list.total"
        :layout="showMobilePage ? 'prev, pager, next, jumper':'total, prev, pager, next, sizes, jumper'"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"/>
    </el-row>
    <!--编辑弹窗  -->
    <el-dialog
      :visible="dialogVisible"
      :show-close="true"
      :close-on-click-modal="true"
      :close="handleClose"
      :before-close="handleClose"
      class="small-common-dialog-size operator-dialog"
    >
      <div class="title-container">
        <Title :title="`${isEdit ? '编辑' : '新建'}未发文通知`" font-size="16px" style="margin-bottom: 16px;"/>
      </div>
      <el-form ref="formRef" :rules="rules" :model="editData" label-width="110px" label-position="left">
        <el-form-item label="规则名称" prop="ruleName">
          <el-input v-model="editData.ruleName" :rows="4" class="width240" size="small" placeholder="请输入" maxlength="50" type="textarea" />
        </el-form-item>
        <el-form-item label="未发文天数" prop="unpublishedDays">
          <el-input v-model="editData.unpublishedDays" class="width240" size="small" placeholder="请输入" type="text" @input="numInputChange" />
        </el-form-item>
        <el-form-item label="通知人员" prop="noticePerson">
          <selectWithUserLoad
            v-model="editData.noticePerson"
            :default-list="editData.noticePerson || []"
            :value-type="'object'"
            key-name="id"
            style="width:240px;"
            label-name="userName"
            placeholder="请选择通知人员"
            multiple
            filterable
            collapse-tags
            clearable
            class="mb10"
          />
        </el-form-item>
        <el-form-item label="循环通知" prop="isLoop">
          <el-radio-group v-model="editData.isLoop">
            <el-radio :label="true">是</el-radio>
            <el-radio :label="false">否</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <div slot="footer" class="center">
        <el-button :disabled="isSubmit" type="primary" size="small" class="ok submit-btn" @click="submit">保存</el-button>
        <el-button class="back-btn cancel-btn-style" type="info" size="small" @click="handleClose" >取消</el-button>
      </div>
    </el-dialog>
  </div>
</template>
<script>
import Title from '@/components/Title';
import EmptyPlaceholder from '@/components/Common/emptyPlaceholder';
import PlainCreateBtn from '@/components/Common/baseComponent/plain-create-btn';
import selectWithUserLoad from '@/components/Common/selectWithUserLoad';
import { showModal } from '@/utils/message';
import { mapState } from 'vuex';
import { format } from '@/filters/date';
import { getUnpublished, delUnpublished, editUnpublished, createUnpublished } from '@/api/setting';

export default {
  components: { EmptyPlaceholder, Title, PlainCreateBtn, selectWithUserLoad },
  filters: { format },
  data() {
    return {
      loading: false,
      perPage: 10,
      page: 1,
      list: {
        items: [],
        total: 0
      },
      editData: {
        ruleName: '',
        isLoop: true,
        unpublishedDays: ''
      },
      dialogVisible: false,
      isSubmit: false,
      rules: {
        ruleName: [{ required: true, trigger: 'blur', message: '请输入规则名称' }],
        unpublishedDays: [{ required: true, trigger: 'blur', message: '请输入未发文天数' }],
        noticePerson: [{ required: true, trigger: 'change', message: '请选择通知人员' }],
        isLoop: [{ required: true, trigger: 'change', message: '请选择循环通知' }]
      }
    };
  },
  computed: {
    ...mapState({
      'showMobilePage': state => state.app.showMobilePage
    }),
    isEdit() {
      return !!this.editData.id;
    }
  },
  created() {
    this.fetchData(true);
  },
  methods: {
    formatUser(arr) {
      if (arr && arr.length) {
        const res = arr.map(item => item.name).join();
        return res;
      } else {
        return '--';
      }
    },
    numInputChange(text) {
      let str;
      str = text.replace(/[^\d.]|\.|^0/g, ''); // 只允许输入正整数
      str = str > 365 ? 365 : str;
      str = str === '' ? null : str;
      this.editData.unpublishedDays = str;
    },
    // 获取列表
    fetchData(reset = false) {
      if (reset) {
        this.page = 1;
      } else {
        this.loading = true;
      }
      const params = {
        page: this.page,
        perPage: this.perPage
      };
      getUnpublished(params).then(res => {
        this.loading = false;
        if (res.code === 200) { this.list = res.data; }
      }).catch(err => {
        this.loading = false;
        console.log(err);
      });
    },
    handleSizeChange(val) {
      this.perPage = val;
      this.fetchData();
    },
    handleCurrentChange(page) {
      this.page = page;
      this.fetchData();
    },
    handleEdit(row) {
      this.openDialog(row);
    },
    handleCopy(row) {
      showModal('请确认是否复制').then(_ => {
        // 复制，手动调新建接口
        const params = {
          ruleName: row.ruleName,
          noticePerson: row.noticePerson.map(item => item.id).join(),
          isLoop: row.isLoop,
          unpublishedDays: row.unpublishedDays,
          isCopy: true
        };
        createUnpublished(params).then(res => {
          if (res.code === 200) {
            this.$message.success('操作成功');
            this.fetchData();
          }
        });
      });
    },
    handleCreate() {
      this.openDialog();
    },
    handleDelete(row) {
      showModal('请确认是否删除').then(_ => {
        delUnpublished(row.id).then(_ => {
          this.$message.success('删除成功');
          if (this.page > 1 && this.perPage * (this.page - 1) + 1 === this.list.total) {
            this.page--;
          }
          this.fetchData();
        });
      });
    },
    openDialog(data = {}) {
      this.dialogVisible = true;
      this.editData = JSON.parse(JSON.stringify(data));
      if (!this.isEdit) {
        this.$set(this.editData, 'isLoop', true);
      } else {
        this.editData.noticePerson = this.editData.noticePerson.map(item => {
          item.userName = item.name;
          return item;
        });
      }
      this.$nextTick(() => {
        this.$refs.formRef && this.$refs.formRef.clearValidate();
      });
    },
    submit() {
      this.$refs.formRef.validate(valid => {
        if (valid) {
          this.handleRequest();
        } else {
          this.$message.warning('请检查信息是否填写完整');
        }
      });
    },
    async handleRequest() {
      this.isSubmit = true;
      const params = JSON.parse(JSON.stringify(this.editData));
      params.noticePerson = params.noticePerson.map(item => item.id).join();
      let res;
      if (this.isEdit) {
        res = await editUnpublished(params.id, params);
      } else {
        res = await createUnpublished(params);
      }
      if (res.code === 200) {
        this.isSubmit = false;
        this.$message.success('操作成功');
        this.handleClose();
        this.fetchData();
      } else {
        this.isSubmit = false;
      }
    },
    handleClose() {
      this.$refs['formRef'].resetFields();
      this.dialogVisible = false;
    }
  }
};
</script>
<style lang="scss" scoped>
.operator-dialog {
  ::v-deep {
    .el-dialog__body {
      padding: 24px 24px 0px 24px !important;
    }
    .el-form-item__label {
      text-align: right;
    }
  }
}
.width240 {
  width: 240px;
}
.operator-btn {
  display: flex;
  &::v-deep {
    .el-button--text:not(:first-child) {
      position: relative;
      &::before {
        content: '';
        width: 1px;
        height: 12px;
        position: absolute;
        left: -6px;
        top: 1px;
        background-color: #ddd;
      }
    }
  }
}
.center {
  display: flex;
  align-items: center;
  justify-content: center;
}
.flex-1 {
  flex: 1;
}
.mb20 {
  margin-bottom: 20px;
}
</style>
